<template>
  <div class='box-wrap-ws-sm'>
    <div class="box-top">
      <div>
        <span>WS仓库说明</span>
        <span>
            号码组成：国家区号+号段+补充位数（每位区间为：0-9）<br>
            号码长度：表示生成的号码总长度（包含国家区号）；根据国家区号和号段的长度自动补充号码的位数。<br>
            生成数量：单个任务生成总数最多不能超过100W。<br>
            <!-- 想了解各个国家地区的号段和区号，具体可通过这个网站查询：<span style="color:#0559FD">https://areacodebase.com/ </span>      -->
        </span>
      </div>
    </div>
    <div class="box-bottom">
        <div class="box-bottom-chil">
          <div class="box-chil-top">
              <div class='form-group-enquire6'>
                <span class="notspan">
                  <span style="content: '*';
                      display: inline-block;
                      margin-right: 4px;
                      line-height: 1;
                      font-family: SimSun;
                      font-size: 14px;
                      color: #ed4014;">*</span>
                      任务名称</span>
                <Input show-word-limit maxlength="20" style="margin-left:15px"  v-model.trim="name" placeholder="请输入任务名称" clearable ></Input>
              </div>
              <div class='form-group-enquire'>
                <span class="notspan">
                  <span style="content: '*';
                  display: inline-block;
                  margin-right: 4px;
                  line-height: 1;
                  font-family: SimSun;
                  font-size: 14px;
                  color: #ed4014;">*</span>
                  国家</span>
                  <el-select v-model="country_id"  @change="initSearchData2()" :disabled="disabled " clearable placeholder="请输入国家" transfer filterable>
                    <el-option :value= row.id  :label= row.full_name v-for="(row,index) in Counlist" :key= index >{{row.short_name}}-{{row.full_name}}</el-option>
                </el-select>
              </div>       
              <img @click="counadd" src="../../assets/images/peach-svg/add (3).svg">
          </div>
          <div class="scroll">                          
              <div v-for="(res,index) in counad" :key="index">
                <div class="box-chil-cen">
                    <div class="box-chil-center">
                          <div class="num">
                            <span class="num-span">国家区号</span>
                            <span class="num-span2">{{res.area_code}}</span>
                          </div>
                          <div class="num2">
                            <span>号码长度</span>
                            <span style="color: #0559FD">{{res.maxnum}}</span>
                            <!-- <Input  v-model.trim="res.length" type="number" :maxlength= res.maxnum placeholder="请输入号段长度" clearable show-word-limit></Input> -->
                          </div>
                          <div class="num2">
                            <span>号段</span>
                            <Input v-model.trim="res.count" type="number"  placeholder="请输入号段" clearable ></Input>
                          </div>
                          <div class="num2">
                            <span>生成数量</span>
                            <Input v-model.trim="res.enable" type="number"  placeholder="请输入生成数量" clearable ></Input>
                          </div>    
                          <!-- <div class="num2" v-if="showlike">
                            <Select v-model="like" clearable transfer filterable>
                                <Option :value= row.id  :label= row.name v-for="row in belike" :key= row.id >{{row.name}}</Option>
                            </Select>                    
                          </div>          -->
                          <div class="num2">
                            <i class="el-icon-error" @click="deldiv(index,res)"></i>
                            <!-- <button >删除</button> -->
                          </div>                         
                    </div>
                </div>
              </div>
            </div>  
          <div class="box-chil-bottom">
            <span class="notspan">开启去重</span>
            <div class="iswit">
              <el-switch
                v-model="value"
                active-color="#13ce66"
                inactive-color="#A5ADBD"
                active-value="1"
                inactive-value="2"
                @change="changeStatus">
            </el-switch>
            </div>
            <div class="istext">
              <span>累计标记的数据有：{{RemarkCount}} 条，<br>
              开启去重生成数据后，被标记的数据则不会生成，且生成的数据会自动保存至云备份存档中。</span>
            </div>
          </div>
          <div class="chil-img" @click='updateInfo(1)'><img  src="../../assets/images/peach-svg/button (3).svg"></div>
        </div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import {commonMixin} from "../../components/ViewInitMixin" //每一个文件都要包含这个
import {TimePicker} from "iview"
import SearchUser from "../searchUser"
import Request from "../../commons/Request"
import bus from "../../commons/EventBus"
import store from "@/commons/store"
export default {
  name: "addUserDetailView",  //!!这块一定要注意，每一个文件都根据资源path来命名
  components:{TimePicker,SearchUser},
  mixins:[commonMixin],
  data() {
    return {
      disabled:false,
      showlike:false,
      like:1,
      belike:[{id:1,name:'同上'},{id:2,name:'同下'}],
      maxnum:{},
      value:"1",
      searchDate:"",
      Counlist:"",
      country_id:"",      
      searchTime:[utils.dateFormat(0,"HH")+"00",utils.dateFormat(0,"HH")+"00"],
      area_code:'',
      counlenght:0,
      list:[],
      totalCnt:0,
      info:{},
      counad:[],      
      counaddres:[],
      name:'',
      num:0,
      length:[],
      count:[],
      enable:[],
      status:1,
      go:false,
      RemarkCount:0,
      segObj:{},
      segList:[],
      tableColumns:[
        {
          title: "序号",
          field: "Day",
          align: 'center',
        },
        {
          title: "任务名称",
          field: "CityId",
          align: 'center',
        },
        {
          title: "任务类型",
          field: "ChannelId",
          align: 'center',
        },
        {
          title: "数据总量",
          field: "Uuid",
          align: 'center',
        },
        {
          title: "可用数量",
          field: "Imsi",
          align: 'center',
        },
        {
          title: "去重数量",
          field: "Imei",
          align: 'center',
        },
        {
          title: "国家",
          field: "Brand",
          align: 'center',
        },
        {
          title: "状态",
          field: "Model",
          align: 'center',
        },
        {
          title: "创建时间",
          field: "CreateTime",
          align: 'center',
          slots: {
            default: ({row},h) => {
              if(row.ChannelId <= 0){
                return [h("div","")]
              } else {
                 return [h("div",utils.dateFormat(row.CreateTime, "yyyy-MM-dd HH:mm:ss"))];
              }
            }
          }
        },
      ],
      
      dateOptions:{
        disabledDate(date){
          return date && date.valueOf() > Date.now();
        },

      },
    };
  },
  computed: {
            ...mapGetters(["UserInfo"]),
        },
  methods: {
    async initView(isMounted){
      if(isMounted){
        this.initSearchData(); 
      } 
    },
    async initSearchData(){
      this.Counlist=[]
      this.maxnum={}
      let Countries = await Request.post("exclude", "GetCountries");//国家
      
      if (Countries.code == 0) {
        Countries.data.list.forEach((item) => {
          this.Counlist.push(item)
          this.$set(this.maxnum,item.id,item)
        })        
      }              
    },    
    async CountryData(){
      let res = await this.RequestPost("getRemarkCount_item",{"country_id":this.country_id}); 
      if(res.code==0){
        this.RemarkCount=res.data
      }else{
        utils.showSureModal({
                "title":"提示",            
                "icon":require('../../assets/images/peach-svg/hongtan.svg'),
                "modalContent":res.data});
      }
    },
    counadd(){
      if(this.country_id==''||this.country_id==undefined){
        return utils.showTip('国家不能为空')
      }else{
        this.CountryData()
        let id = this.maxnum[this.country_id].area_code
        this.area_code = this.maxnum[this.country_id].area_code
        let length = this.maxnum[this.country_id].number_bit_count//号码最大长度
        let lastenable = ''
            lastenable = this.counad[this.counad.length-1]//获取最后一个数组
        if(lastenable!=undefined){
           lastenable = this.counad[this.counad.length-1].enable       
        }
        let count={
            area_code:id,
            enable:lastenable,
            length:String(length),
            count:"",
            maxnum:length
        }
        this.counad.push(count)  
        if (this.counad.length>0) {
          this.disabled=true
        }
        if (this.counad.length>=2) {
            this.showlike=true
        }else{
          this.showlike=false
        }
      }
    }, 
    changeStatus(data){
      this.status=data
    },
    initSearchData2(){
      let id = this.country_id
      bus.$emit('sub',id)      
      this.counad = []
      this.length = []
      this.count = []
      this.enable = []
    },
    cutting(data){
      let a= []
      let length= []
      a.push(data)  
      a.forEach(res =>{
        length=res
      })

    },
    async updateInfo(type) {
      
      // utils.showLoading()
      this.length = []
      this.count = []
      this.enable = []         
      let code = -1;
      let actionName = '';
      let tipText = '';
      let name = this.name
      let length,count,enable = []
      let counaddres = this.counad
      
      let id = this.country_id
      if(counaddres.length!=0){
        if(counaddres.length==1){
          let num =counaddres[0]
          length=num.length//号码长度
          count=num.count
          enable=num.enable

          if(count==''||enable==''||length==''){
            throw utils.showTip('输入框不能为空');
          }                
          //国家区号长度+号段长度
          let numad = Number(this.area_code.length)+Number(count.length)
          //生成数量最大数
          let addlenght = length - numad
          //国家区号长度+号段长度 不能大于 号码长度 或者 生成数量不能大于剩下长度
          if(length==0){
            utils.showSureModal({"icon":require('../../assets/images/peach-svg/bluegth.svg'),
            "modalContent":"请联系客服",
            "title":"提示"});
          }      
        }else{
          counaddres.forEach(res => {
            if(res.count==''||res.length==''||res.enable==''){
              throw utils.showTip('输入框不能为空');
            }
            this.length.push(res.length)
            this.count.push(res.count)
            this.enable.push(res.enable)              
          })
            length=this.length.join('|') 
            count=this.count.join('|')
            enable=this.enable.join('|')
        }
      
      let info={
        name:name,
        country_id:id,
        area_code:this.area_code,
        length:length,        
        count:count,        
        enable:enable,        
        status:this.status,        
      }
      let postData = utils.cloneObj(info);
      
      if(this.name == ''){
        return utils.showTip('任务名称不能为空')
      }
      if (type==1) {
        actionName = 'createTask_item';        
        tipText = '创建成功！';    
        postData = {
          "name":postData.name,
          "country_id":postData.country_id,
          "area_code":postData.area_code,
          "segment":postData.count,
          "de_duplication_enable":postData.status,
          "generation_number_length":postData.length,
          "generation_number_count":postData.enable
          };
        }
        let res = await this.RequestPost(actionName, postData);
        code = res.code;
        if (code == 0) {
          let res2 = await Request.post("number/tasks", "queryTasks_list");
          utils.hideFormPage(this.formPopIndex);
          await utils.sleepMs(1000);
          // this.onSearchGetList();
          setTimeout(() => {   
            this.name="",
            this.country_id="",
            this.counad=[]
            this.disabled=false
            bus.$emit("number",res2.data.list)
            bus.$emit('search','')        
          }, 300);
          utils.showTip(tipText);
        }
        else{
          if(res.data.notice!=undefined){
            this.segObj={}
            this.segList=[]
            utils.showSureModal({
                "title":"提示",            
                "icon":require('../../assets/images/peach-svg/hongtan.svg'),
                "modalContent":res.data.notice},(res2)=>{
              let code = res2.code;
              if(code==0){
                res.data.seg.forEach(item => {
                  this.$set(this.segObj,item.no,item.max_count)
                  this.segList.push({"id":item.no,"count":item.max_count})
                });
                
                this.counad.forEach(element => {
                    this.segList.forEach((itemm,index)=> {
                      if(itemm.id==element.count){
                      this.$set(this.counad,index,{"area_code":element.area_code,"count":element.count,"length":element.length,"maxnum":element.maxnum,"enable":this.segObj[element.count]})
                    }
                  }
                  );
                });
                
              }
            });
          }else{
            throw utils.showTip(res.data);
          }
          
        }
      } else{
        throw utils.showTip('请完善任务信息！');
      }
    },   
    deldiv(index,res){
        this.counad.splice(index,1)
        if(this.counad.length==0){
          this.disabled=false
        }
    }    
  },
};
</script>  